import { getActivityDetail, receiveCoupon } from "@src/api/marketing";
import { getUserPhone } from '@src/api/mall/address'
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import base from "@src/store/base";
import location from "@src/store/location";
import member from '@src/store/member'
import { getNearbyShopList } from "@src/api/shop";
import { minuteToHour } from "@src/common/dateUtils";
import { BizCodeOptions, PaymentOptions, weekNumStringToChinese } from "@src/common/utils";
import bank from "./bank.js"
import $math from "@src/common/math";
import router from "@src/router";
import dayjs from "dayjs";
import {payCouponSendQuery} from "@src/api/coupon";
const extConfig = wx.getExtConfigSync();
// dayjs.extend(RelativeTime)
Component({
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor', 'perms'],
  }, {
    store: location,
    fields: ['latitude', 'longitude'],
    actions: ['getLocation']
  }, {
    store: member,
    fields: ['categoryId'],
  }],
  data: {
    //true 为演示数据
    flag: null,
    //券是否已经领取
    ifGet: false,
    //券列表
    couponList: [],
    //当前卡是否可以领取
    cardAuth: true,
    //当前时间活动是否开始
    timeAuth: true,
    categoryId: [],
    categoryToOpen: {},
    //按钮文字
    btnTitle: null,
    //倒计时定时器
    timer: null,
    //活动开始剩余时间
    residueTime: "",
    //
    phone: null,
    isClick: false,
    activityCode: null,
  },
  methods: {
    onLoad(options) {
      console.log('options', options)
      let { activityCode } = options;
      console.log('activityCode', activityCode)
      this.setData({ activityCode: activityCode });
    },
    onLogin() {
      this.fetchData().then(res => {
        this.getLocation().then(res => {
          this.getShopList();
        }).catch(err => {
          this.getShopList();
        });
      });
    },
    //判断是否需要跳webview
    handleWebview(params) {
          let couponIds =[]
          params.forEach((item,index)=>{
          if(item.couponType === "cash_wx_pay"){
            couponIds.push(item.id)
          }
      })
      return new Promise((resolve, reject) => {
        if (couponIds.length>0) {
          payCouponSendQuery(couponIds).then(res => {
            if (res.code == 0) {
              if (res.data.needJump) {
                let urlParams = { url: res.data.webViewUrl }
                router.push({
                  name: 'mall/inside-url', params: urlParams,
                  events: {
                    webViewSuccess: (data) => {
                      resolve(true)
                    },
                  }
                });
              } else {
                resolve(true)
              }
            }
          })
        } else { resolve(true) }
      })
    },
    fetchData() {
      let data = { activityCode: this.data.activityCode }
      return getActivityDetail(data).then(res => {
        let activity = res.data.activity;
        activity.award = res.data.awards;
        activity.todayIssued = res.data.todayIssued;
        activity.singleItemRules = res.data.singleItemRules;
        this.setData({ couponList: res.data.couponList });

        if(res.data.activity.activityType === 4 ){
          this.handleWebview(this.data.couponList)
        }

        if (this.data.couponList) { this.resetTime(this.data.couponList) }
        this.resetData(activity);
        //领券活动判断是否可以领取
        if (activity.activityType === 4 && res.data.categoryId) {
          this.handleCardAuth(res.data.categoryId, res.data.categoryToOpen)
        }
        this.handleDateAuth(activity)
      })
    },
    //处理券列表时间
    resetTime(list) {
      if (list.length > 0) {
        list.forEach(item => {
          let endTime = item.endTime;
          item.endTime = dayjs(endTime).format("YYYY-MM-DD");
        })
        this.setData({ couponList: list })
      }
    },
    //判断当前卡资格是否可以领取
    handleCardAuth(categoryId, categoryToOpen) {
      let nowCategoryId = this.data.categoryId;
      if (categoryId.length < 1) { return; }
      if (categoryId.includes(nowCategoryId)) {
        this.setData({ cardAuth: true })
      } else {
        let st = categoryId[0];
        this.setData({ cardAuth: false, btnTitle: "成为" + categoryToOpen[st] + "会员即可领取" });
      }
    },
    //判断当前日期活动是否开始
    handleDateAuth(activity) {
      let self = this;
      //获取当前的时间
      let now = dayjs();
      let startTime = dayjs(activity.startTime);
      // //todo 
      // let startTime = dayjs('2021-01-22:17:31');
      let temp = now.diff(startTime, 'day');
      console.log('temp', temp)
      /**
       * 这里分两种情况 1. temp>0活动一定是开始了
       *                       2.temp=0 活动可能明天开始或者今天已经开始，要做第二次判断
       */
      if (temp > 0) {
        this.setData({ timeAuth: true })
      } else if (temp == 0) {
        let nowMin = now.diff(startTime, 'minute');
        //活动已经开始
        if (nowMin > 0) {
          this.setData({ timeAuth: true })
        } else { //24小时内开始，要设置定时器
          self.setData({
            timer: setInterval(function () {
              // self.useTime(startTime)
              self.useTime(startTime)
            }, 1000)
          })
          this.setData({ timeAuth: false })
        }
        console.log('nowMin', nowMin)
      } else {
        //temp < 0
        // xxx天后可领取
        this.setData({ residueTime: Math.abs(temp) + "天" });
        console.log("residueTime", this.data.residueTime)
        this.setData({ timeAuth: false })
      }
      console.log('now-startTime', now.diff(startTime, 'day'))
      console.log('startTime', startTime)
      console.log('timeAuth', this.data.timeAuth)

    },
    useTime(startTime) {
      console.log('startTime1', startTime)
      let now = dayjs();
      let hour = now.diff(startTime, 'hour');//时
      let m = 0;//分
      let s = 0;//秒

      hour = Math.abs(hour)
      console.log('hour', hour)
      // if (hour > 0) {
      let addNowHour = now.add(hour, 'hour');
      console.log('addNowHour', addNowHour);
      m = addNowHour.diff(startTime, 'minute');
      m = Math.abs(m);
      let addNowMin = addNowHour.add(m, 'minute');
      console.log('addNowMin', addNowMin);
      s = Math.abs(addNowMin.diff(startTime, 'second'));
      console.log('s', s);
      console.log('m', m)
      console.log('hour', hour);

      if (hour == 0) {
        this.setData({
          residueTime: m + '分' + s + '秒'
        })
      } else {
        this.setData({
          residueTime: hour + '时' + m + '分' + s + '秒'
        })
      }
      //倒计时为空则清除定时器
      if (hour == 0 && m == 0 && s == 0) {
        this.setData({ timeAuth: true });
        clearInterval(this.data.timer)
      }
    },
    // 格式化详情数据
    resetData(data) {
      console.log('data', data)
      // 时间
      if (data.useRule !== 1) {
        let ruleDataDateArr = [];
        let ruleDataTimeArr = [];
        data.ruleDataTime = data.ruleDataTime.split(",");
        data.ruleDataTime.forEach(v => {
          ruleDataTimeArr.push({
            time: [
              minuteToHour(v.split("-")[0]),
              minuteToHour(v.split("-")[1])
            ]
          });
        });
        data.ruleDataTime = ruleDataTimeArr;
        switch (data.useRule) {
          case 2:
            data.ruleDataWeek = weekNumStringToChinese(data.ruleDataWeek);
            data.ruleDataDate = [{ date: "" }];
            break;
          case 3:
            data.ruleDataTime = [{ time: ["00:00", "23:59"] }];
            data.ruleDataDate = data.ruleDataDate.split(",");
            data.ruleDataDate.forEach(v => {
              ruleDataDateArr.push({
                date: [v.split(":")[0], v.split(":")[1]]
              });
            });
            data.ruleDataDate = ruleDataDateArr;
            break;
        }
      }
      // 奖励规则
      data.award.forEach(v => {
        v.awardText = "";
        // 消费金额
        if (data.activityType === 3) {
          if (v.calculateType === 1) {
            v.awardText += `消费满${v.amount / 100}元返${v.balance / 100}元微信红包`;
          } else {
            v.awardText += `消费每满${v.amount / 100}元返${v.balance / 100}元微信红包`;
          }
        } else {
          if (v.calculateType === 1) {
            v.awardText += `消费满${v.amount / 100}元赠送`;
          } else {
            v.awardText += `消费每满${v.amount / 100}元赠送`;
          }
          // 余额
          if (v.bonusBalance) {
            v.awardText += `${v.balance / 100}元`;
            v.awardText += v.bonusPoint ? "，" : "";
          }
          // 积分
          if (v.bonusPoint) {
            v.awardText += `${v.points}积分`;
            v.awardText += v.bonusCoupon ? "，" : "";
          }
          // 券
          if (v.bonusCoupon) {
            v.couponData = JSON.parse(v.couponData);
            v.couponData.forEach((couponItem, couponIndex) => {
              if (couponIndex !== 0) v.awardText += "，";
              v.awardText += `【${couponItem.name}】${couponItem.num}张`;
            });
          }
        }
        v.awardText += "。";
        console.log(v);
      });

      //  活动说明数组 explanList
      data.explanList = [];
      // 场景
      if (data.bizType) {
        let bizTypeText = "仅限";
        data.bizType.split(",").forEach((code, index) => {
          BizCodeOptions.forEach(item => {
            if (item.key == code) {
              bizTypeText += item.label;
              if (index !== 0) bizTypeText += "，";
            }
          });
        });
        bizTypeText += "场景可用。";
        data.explanList.push(bizTypeText);
      } else {
        data.explanList.push("全部场景可用。");
      }

      // 支付方式
      // if (data.activityType === 3) {
      if (data.payType) {
        let payTypeText = "仅限";
        data.payType.split(",").forEach((code, index) => {
          if (PaymentOptions[Number(code)]) {
            if (index !== 0) payTypeText += "，";
            payTypeText += PaymentOptions[Number(code)];

          }
        });
        payTypeText += "可用。";
        data.explanList.push(payTypeText);
      } else {
        data.explanList.push("全部支付方式可用。");
      }

      // 参与付款方式
      //todo
      if (data.limitPay) {
        if (data.limitPay === 1) {
          data.explanList.push("全部付款方式可参与。");
        } else {
          let bankCode = data.bankCode.split(",");
          let bankArr = [];
          console.log('bankCode', bankCode);
          let bankTemp = bank.bank;
          if (data.limitPay === 2) {
            for (let k in bankTemp) {
              bankCode.forEach(item => {
                if (k == item) { bankArr.push(bankTemp[k]) }
              })
            }
            data.explanList.push("指定参与付款方式银行卡列表:" + bankArr.join(","));
            console.log('bankArr', bankArr)
          } else if (data.limitPay === 3) {
            for (let k in bankTemp) {
              bankCode.forEach(item => {
                if (k != item) { bankArr.push(bankTemp[k]) }
              })
            }
            data.explanList.push("指定参与付款方式银行卡列表:" + bankArr.join(","));
            console.log('bankArr', bankArr)
          }
        }
      }
      // 限制
      let userFrequencyText = "单个用户";
      if (data.frequencyDay != -1) {
        userFrequencyText += `每天可参与活动${data.frequencyDay}次，`;
      }
      if (data.frequencyWeek != -1) {
        userFrequencyText += `每周可参与活动${data.frequencyWeek}次，`;
      }
      if (data.frequencyMonth != -1) {
        userFrequencyText += `每月可参与活动${data.frequencyMonth}次，`;
      }
      if (data.frequencyAll != -1) {
        userFrequencyText += `活动期间累计可参与${data.frequencyAll}次，`;
      }
      if (userFrequencyText !== "单个用户") {
        data.explanList.push(userFrequencyText.slice(0, -1) + "。");
      }

      // 详情备注
      if (data.remark) {
        data.explanList.push(data.remark);
      }

      // 门店
      data.shop = data.shop ? data.shop.split(",") : [];

      // 名额百分比
      if (data.budget !== -1) {
        data.remainBudgetPercentage = $math.div(data.remainBudget, data.budget, 0);
        data.remainBudgetPercentage = $math.mul(
          data.remainBudgetPercentage,
          100,
          0
        );
      }
      // 当天百分比
      if (data.perdayBudget !== -1) {
        let todayRemainBudgetPercentage = 0;
        todayRemainBudgetPercentage = $math.div(data.perdayBudget - data.todayIssued, data.perdayBudget, 0);
        data.todayRemainBudgetPercentage = $math.mul(todayRemainBudgetPercentage, 100, 0);
      }
      // 赋值
      //todo
      // data.participant = 4;

      this.setData({ detail: data })
      console.log('detail.explanList', this.data.detail.explanList)
      console.log('detail', this.data.detail)
    },
    handleOpenMap(e) {
      let data = e.currentTarget.dataset.item
      wx.openLocation({
        latitude: data.latitude,
        longitude: data.longitude,
        name: data.name,
        address: data.address
      });
    },
    handleShowShops(e) {
      let shopIds = e.currentTarget.dataset.shop;
      let list = this.data.shopList;
      // list.forEach(item => {
      //   console.log('item', item)
      //   if (item.distance) {
      //     item.distance = parseInt(item.distance)
      //     if (item.distance < 1000) {
      //       item.distance = item.distance.toFixed(2) + "米"
      //     } else {
      //       item.distance = (Math.round(item.distance / 100) / 10).toFixed(1) + "km"
      //     }
      //   }
      // })
      // console.log('list', list);
      this.selectComponent("#shop-list").open(shopIds, list);
    },
    getShopList() {
      this.updateStoreBindings()
      let params = {};
      if (this.data.latitude) {
        params.latitude = this.data.latitude;
        params.longitude = this.data.longitude;
      }

      params.idList = this.data.detail.shop;
	  params.businessId = extConfig.businessId
      getNearbyShopList(params).then(res => {
        if (res.data.length > 0) {
          res.data.forEach(item => {
            if (item.distance) {
              item.distance = parseInt(item.distance)
              if (item.distance < 1000) {
                item.distance = item.distance.toFixed(2) + "米"
              } else {
                item.distance = (Math.round(item.distance / 100) / 10).toFixed(1) + "km"
              }
            }
          })

          // res.data[0].distance = res.data[0].distance ? (res.data[0].distance / 1000).toFixed(2) : 0;
        }
        this.setData({ shopList: res.data });
      });
    },
    getCouponFunc() {
      let self = this;
      if (this.data.ifGet) { return; }
      if (this.data.isClick) { setTimeout(() => { self.setData({ isClick: false }) }, 1500); return; } else { self.setData({ isClick: true }) }
      //指定银行卡
      if (this.data.detail.participant === 5) { this.selectComponent("#pop-out").open(1); }
      else {
        this.receiveCouponFunc()
      }
    },
    //监听券是否已经被领取
    getCouponFun() {
      this.setData({ ifGet: true })
    },
    //去开卡页面
    openCard() {
      router.push({ name: 'indexChooseCard' })
    },
    //获取手机号
    getPhoneNumber(e) {
      let data = { ivStr: e.detail.iv, encryptedData: e.detail.encryptedData }
      getUserPhone(data).then(res => {
        if (res.code === 0) { this.setData({ phone: res.data }); this.receiveCouponFunc() } else {
          wx.showToast({ title: '手机号获取失败,请稍后重试', icon: 'none' })
        }
      })
    },
    //领取卡券
    receiveCouponFunc() {
      let self = this;
      let temp = {
        activityCode: this.data.activityCode,
        bankNo: null,
        bankUser: null,
        phone: this.data.phone
      };
      receiveCoupon(temp).then(res => {
        let params = res.data.params;
        if (params) {
          self.selectComponent("#pop-out").open(2, self.data.couponList, params);
        } else {
          wx.showToast({
            title: '领取成功',
            icon: 'success',
            duration: 2000
          })
          self.setData({ ifGet: true })
          // self.showReceiveCoupon(prototype, params, codes)
        }
      }).catch(err => {

      })
    },
    onUnload() {
      if (this.data.timer) { clearInterval(this.data.timer) }
    }
  }
})
